'use client'

import { LocalizationProvider } from '@mui/x-date-pickers'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import dayjs from 'dayjs'
import 'dayjs/locale/ru'
import relativeTime from 'dayjs/plugin/relativeTime'
import { type PropsWithChildren, useState } from 'react'
import { z } from 'zod'
import zu from 'zod_utilz'

import { zodErrorMap } from '@/config/zod.config'

dayjs.extend(relativeTime)
dayjs.locale('ru')

z.setErrorMap(zu.makeErrorMap(zodErrorMap))

export function Providers({ children }: PropsWithChildren) {
	const [client] = useState(
		new QueryClient({
			defaultOptions: {
				queries: {
					refetchOnWindowFocus: false
				}
			}
		})
	)

	return (
		<QueryClientProvider client={client}>
			<LocalizationProvider
				dateAdapter={AdapterDayjs}
				adapterLocale='ru'
			>
				{children}
			</LocalizationProvider>
			<ReactQueryDevtools initialIsOpen={false} />
		</QueryClientProvider>
	)
}
